package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.TrendsModel;
import com.jtech.together.mvp.contract.AddTrendsContract;
import com.jtech.together.util.BmobUtil;
import com.jtech.together.util.luban.Luban;

import java.io.File;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 增加动态
 * Created by wuxubaiyang on 2017/5/11.
 */
public class AddTrendsPresenter implements AddTrendsContract.Presenter {
    private Context context;
    private AddTrendsContract.View view;

    public AddTrendsPresenter(Context context, AddTrendsContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
    }

    @Override
    public void publishTrends(String content, List<String> images, BmobGeoPoint location, String address) {
        if (isAllHttpUrl(images)) {
            publish(content, images, location, address);
        } else {
            //迭代的方式上传图片
            uploadImage(content, images, location, address, 0);
        }
    }

    /**
     * 发布
     *
     * @param content
     * @param images
     * @param location
     * @param address
     */
    private void publish(String content, List<String> images, BmobGeoPoint location, String address) {
        TrendsModel trendsModel = new TrendsModel();
        trendsModel.setUser(UserManager.getCurrentUser());
        trendsModel.setContent(content);
        trendsModel.setImages(images);
        trendsModel.setAddress(address);
        trendsModel.setLocation(location);
        trendsModel.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (null == e) {
                    view.publishSuccess(objectId);
                } else {
                    view.publishFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }

    /**
     * 上传图片
     *
     * @param content
     * @param images
     * @param location
     * @param address
     * @param position
     */
    private void uploadImage(final String content, final List<String> images, final BmobGeoPoint location, final String address, final int position) {
        if (images.size() > position) {
            //判断是否为网络图片
            final String imageUrl = images.get(position);
            if (!(imageUrl.startsWith("http://") || imageUrl.startsWith("https://"))) {
                //使用luban进行图片压缩
                Luban.get(context)
                        .load(new File(imageUrl))
                        .putGear(Luban.THIRD_GEAR)
                        .asObservable()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<File>() {
                            @Override
                            public void accept(File file) throws Exception {
                                //文件上传
                                uploadFile(file, imageUrl, images, content, location, address, position);
                            }
                        });
            } else {
                uploadImage(content, images, location, address, position + 1);
            }
        } else {
            //迭代完成，则开始上传
            publish(content, images, location, address);
        }
    }

    /**
     * 压缩完图片就开始上传
     *
     * @param file
     * @param imageUrl
     * @param images
     * @param content
     * @param location
     * @param address
     * @param position
     */
    private void uploadFile(File file, final String imageUrl, final List<String> images, final String content,
                            final BmobGeoPoint location, final String address, final int position) {
        //将压缩后的图片上传
        final BmobFile bmobFile = new BmobFile(file);
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    String avatarUrl = bmobFile.getFileUrl();
                    view.updateImageUrl(imageUrl, avatarUrl, position + 1, images.size());
                    images.set(position, avatarUrl);
                    //继续迭代
                    uploadImage(content, images, location, address, position + 1);
                } else {
                    view.publishFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }

            @Override
            public void onProgress(Integer value) {
                Log.i("avatarUploadProgress：", value + "");
            }
        });
    }

    /**
     * 判断集合中所有地址是否都是网络图片
     *
     * @param images
     * @return
     */
    private boolean isAllHttpUrl(List<String> images) {
        boolean flag = true;
        for (int i = 0; i < images.size(); i++) {
            String imageUrl = images.get(i);
            if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
                flag = true;
            } else {
                flag = false;
                break;
            }
        }
        return flag;
    }
}